package it.tcm.TeacherClassMate.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import javax.xml.bind.JAXBElement;
import org.apache.log4j.Logger;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.Part;
import org.docx4j.openpackaging.parts.PartName;
import org.docx4j.openpackaging.parts.Parts;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.Body;
import org.docx4j.wml.Document;
import org.docx4j.wml.Text;

public class TrimDocx {
	
	private Logger logger = Logger.getLogger(this.getClass().getName());		
	private final String XPATH_TO_SELECT_TEXT_NODES = "//w:t";	
	private final String XPATH_TO_SELECT_MATH_NODES = "w:p[w:pPr/w:pStyle/@w:val='Formula']";
	private final String XPATH_TO_SELECT_MATH_NODES_2 = "w:p[m:oMathPara]";
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public byte[] trim(InputStream inputStream,String docxFileDir) {
		
		byte[] fileContent = null;
		try {

			// Populate the Strings that will replace the template text
			Map map = new HashMap();
			map.put("Project", "BP Mount");
			map.put("date", "21-Mar-2011");
	
			WordprocessingMLPackage template = WordprocessingMLPackage.load(inputStream);
			
			Parts parts = template.getParts();
			HashMap partsMap = parts.getParts();
			PartName partName = null;
			Part part = null;
			
			Set set = partsMap.keySet();
			for (Iterator iterator = set.iterator(); iterator.hasNext();) {
				PartName name = (PartName) iterator.next();
				if (name.getName().equalsIgnoreCase("/word/media/image1.png")) {
					part = (Part)partsMap.get(name);
					partName = name;
				}
			}
			if(part !=null && partName !=null ){
				part = (Part)partsMap.get(partName);
				BinaryPart binaryPart = (BinaryPart) part;
				//binaryPart.setBinaryData(fileToBytes(fileToReplace));
			}
						
//			List texts = template.getMainDocumentPart().getJAXBNodesViaXPath(XPATH_TO_SELECT_TEXT_NODES, false);
//			for (Object obj : texts) {
//				Text text = (Text) ((JAXBElement) obj).getValue();
//				String textValue = text.getValue();
//				for (Object key : map.keySet()) {
//					textValue = textValue.replaceAll("\\$\\{" + key + "\\}",(String) map.get(key));
//				}
//				text.setValue(textValue);
//			} 
			
			
			MainDocumentPart documentPart = template.getMainDocumentPart();
			String xpath = "//w:p";
			List<Object> listp = documentPart.getJAXBNodesViaXPath(xpath, false);
			
			// Create the package
			WordprocessingMLPackage wordMLPackage = new WordprocessingMLPackage();
			// Create the main document part (word/document.xml)
			MainDocumentPart wordDocumentPart = new MainDocumentPart();
			// Create main document part content
			ObjectFactory factory = Context.getWmlObjectFactory();
			org.docx4j.wml.Body body = factory .createBody();
			org.docx4j.wml.Document wmlDocumentEl = factory .createDocument();
			wmlDocumentEl.setBody(body);
			// Put the content in the part
			wordDocumentPart.setJaxbElement(wmlDocumentEl);
			
			List<org.docx4j.wml.P> arrayOfParag = new ArrayList<org.docx4j.wml.P>();
			
			// Create the paragraph
			org.docx4j.wml.P para = factory.createP();
			// Create the text element
			org.docx4j.wml.Text t = factory.createText();
			t.setValue("ESERCIZIO NUMERO 1");
			// Create the run
			org.docx4j.wml.R run = factory.createR();
			run.getContent().add(t);
			para.getContent().add(run);
			arrayOfParag.add(para);
			
			for (Object obj : listp) {
				org.docx4j.wml.P para0 = (org.docx4j.wml.P)obj;
				List<Object> listr = para0.getContent();
				if (listr != null && listr.size() != 0) {
					arrayOfParag.add(para0);
				}
			}
			
			// Create the paragraph
			org.docx4j.wml.P para2 = factory.createP();
			// Create the text element
			org.docx4j.wml.Text t2 = factory.createText();
			t2.setValue("ESERCIZIO NUMERO 2");
			// Create the run
			org.docx4j.wml.R run2 = factory.createR();
			run2.getContent().add(t2);
			para2.getContent().add(run2);
			arrayOfParag.add(para2);
			
			body.getContent().addAll(arrayOfParag);
			
			
			// Add the main document part to the package relationships
			// (creating it if necessary)
			wordMLPackage.addTargetPart(wordDocumentPart);
			
			File file = new File(docxFileDir + "//temp.docx");
		    wordMLPackage.save(file);
		    FileInputStream fin = new FileInputStream(file);
		    fileContent = new byte[(int)file.length()];
		    fin.read(fileContent);

			// Save it
			//wordMLPackage.save(  new java.io.File("c:/Tmp/helloworld.docx") );
					
		
		} catch (Exception e) {
			logger.error("Exception " + e.getMessage());
		}

		return fileContent;
		
		
	}

}
